import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { orders, orderItems, customers, products } from '@/lib/schema';
import { eq, desc, sql } from 'drizzle-orm';

export async function GET() {
  try {
    const allOrders = await db
      .select({
        id: orders.id,
        orderNumber: orders.id,
        customerName: customers.name,
        totalAmount: orders.totalAmount,
        status: orders.status,
        createdAt: orders.createdAt,
        itemsCount: sql<number>`count(${orderItems.id})`
      })
      .from(orders)
      .leftJoin(customers, eq(orders.customerId, customers.id))
      .leftJoin(orderItems, eq(orders.id, orderItems.orderId))
      .groupBy(orders.id)
      .orderBy(desc(orders.createdAt));

    return NextResponse.json(allOrders);
  } catch (error) {
    console.error('获取订单列表失败:', error);
    return NextResponse.json(
      { error: '获取订单列表失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // 计算订单总额
    let totalAmount = 0;
    if (body.items && Array.isArray(body.items)) {
      totalAmount = body.items.reduce((sum: number, item: any) => {
        return sum + (item.price || 0) * (item.quantity || 0);
      }, 0);
    }

    const [newOrder] = await db
      .insert(orders)
      .values({
        customerId: body.customerId,
        totalAmount: totalAmount,
        status: body.status || 'pending'
      })
      .returning();

    // 添加订单商品
    if (body.items && Array.isArray(body.items)) {
      for (const item of body.items) {
        await db.insert(orderItems).values({
          orderId: newOrder.id,
          productId: item.productId,
          quantity: item.quantity,
          price: item.price,
          subtotal: item.price * item.quantity
        });
      }
    }

    return NextResponse.json({
      ...newOrder,
      message: '订单创建成功'
    }, { status: 201 });
  } catch (error: any) {
    console.error('创建订单失败:', error);
    return NextResponse.json(
      { error: '创建订单失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}